##  R Beginner's Guide
##  Chapter 5 - Assessing the Situation
##  by John M. Quick
##  created June 8, 2010

##  MAKING AN INITIAL INFERENCE FROM OUR DATA

# set the R working directory
# replace the sample location with one that is relevant to you
setwd("C://Novayre//GIT-Projects//book-Statistical Analysis With R//Chapter 05")

# load the chapter 5 workspace
load("rBeginnersGuide_Ch_05_ReadersCopy.RData")
# verify the contents of the workspace
ls()

# mean number of Shu soldiers engaged in battle
meanSoldiersShu
# mean number of Wei soldiers engaged in battle
meanSoldiersWei

# ratio of mean Wei soldiers to Shu soldiers
meanSoldierRatioWeiShu <- meanSoldiersWei / meanSoldiersShu
# display the contents of meanSoldierRatioWeiShu
meanSoldierRatioWeiShu

# how many Wei soldiers would we expect to engage in battle if our Shu forces numbered 100,000?
100000 * meanSoldierRatioWeiShu

# #  EXAMINING OUR DATA

# display all of our battle history data
battleHistory

# our battleHistory dataset contains seven columns
# Method contains the type of battle technique employed (headToHead, surround, ambush, or fire)
# Rating contains a measure of the Shu army's performance on a scale from 0 to 100
# SuccessfullyExecuted contains a yes (Y) or no (N) value indicating whether the battle method was executed successfully
# Result tells us whether the battle ended in Victory or Defeat
# ShuSoldiersEngaged presents the number of soldiers who engaged in combat for the Shu army during each battle
# WeiSoldiersEngaged is identical to ShuSoldiersEngaged, but for the Wei forces
# DurationInDays indicates how long each battle lasted, in days

# #  CREATING A SUBSET FROM A LARGE DATASET

# use the subset(data, ...) function to create a subset from a larger dataset
# create a subset that isolates our head to head combat data
subsetHeadToHead <- subset(battleHistory, battleHistory$Method == "headToHead")
# display the contents of the head to head subset
subsetHeadToHead

# create a subset that isolates our surround combat data
subsetSurround <- subset(battleHistory, battleHistory$Method == "surround")
# display the contents of the surround subset
subsetSurround

# create a subset that isolates our ambush combat data
subsetAmbush <- subset(battleHistory, battleHistory$Method == "ambush")
# display the contents of the surround subset
subsetAmbush

# create a subset that isolates our fire attack combat data
subsetFire <- subset(battleHistory, battleHistory$Method == "fire")
# display the contents of the surround subset
subsetFire
 
# #  DERIVING SUMMARY STATISTICS

# use mean(data) to calculate the mean of a given dataset
# what was the mean number of Shu soldiers engaged in past head to head conflicts?
meanShuSoldiersHeadToHead <- mean(subsetHeadToHead$ShuSoldiersEngaged)
# what was the mean number of Wei soldiers engaged in past head to head conflicts?
meanWeiSoldiersHeadToHead <- mean(subsetHeadToHead$WeiSoldiersEngaged)
# what was the mean duration (in days) of past head to head conflicts?
meanDurationHeadToHead <- mean(subsetHeadToHead$DurationInDays)
# display the calculated means
meanShuSoldiersHeadToHead
meanWeiSoldiersHeadToHead
meanDurationHeadToHead

# use sd(data) to calculate the standard deviation of a given dataset
# what was the standard deviation of Shu soldiers engaged in past head to head conflicts?
sdShuSoldiersHeadToHead <- sd(subsetHeadToHead$ShuSoldiersEngaged)
# what was the standard deviation of Wei soldiers engaged in past head to head conflicts?
sdWeiSoldiersHeadToHead <- sd(subsetHeadToHead$WeiSoldiersEngaged)
# what was the standard deviation of duration (in days) in past head to head conflicts?
sdDurationHeadToHead <- sd(subsetHeadToHead$DurationInDays)
# display the calculated standard deviations
sdShuSoldiersHeadToHead
sdWeiSoldiersHeadToHead
sdDurationHeadToHead

# use range(data, ...) to calculate the range of a given dataset
# what was the range of Shu soldiers engaged in past head to head conflicts?
rangeShuSoldiersHeadToHead <- range(subsetHeadToHead$ShuSoldiersEngaged)
# what was the range of Wei soldiers engaged in past head to head conflicts?
rangeWeiSoldiersHeadToHead <- range(subsetHeadToHead$WeiSoldiersEngaged)
# what was the range of duration (in days) of past head to head conflicts?
rangeDurationHeadToHead <- range(subsetHeadToHead$DurationInDays)
# display the calculated ranges
rangeShuSoldiersHeadToHead
rangeWeiSoldiersHeadToHead
rangeDurationHeadToHead

# use the summary(object) function to generate a summary of a given object
# general summary of our head to head combat data
summaryHeadToHead <- summary(subsetHeadToHead)
# display the head to head subset summary
summaryHeadToHead

# calculate summary statistics (means, standard deviations, ranges) for each battle method
# also generate a summary of each subset
# display the contents of each variable

# surround summary statistics
# means
meanShuSoldiersSurround <- mean(subsetSurround$ShuSoldiersEngaged)
meanShuSoldiersSurround
meanWeiSoldiersSurround <- mean(subsetSurround$WeiSoldiersEngaged)
meanWeiSoldiersSurround
meanDurationSurround <- mean(subsetSurround$DurationInDays)
meanDurationSurround
# standard deviations
sdShuSoldiersSurround <- sd(subsetSurround$ShuSoldiersEngaged)
sdShuSoldiersSurround
sdWeiSoldiersSurround <- sd(subsetSurround$WeiSoldiersEngaged)
sdWeiSoldiersSurround
sdDurationSurround <- sd(subsetSurround$DurationInDays)
sdDurationSurround
# ranges
rangeShuSoldiersSurround <- range(subsetSurround$ShuSoldiersEngaged)
rangeShuSoldiersSurround
rangeWeiSoldiersSurround <- range(subsetSurround$WeiSoldiersEngaged)
rangeWeiSoldiersSurround
rangeDurationSurround <- range(subsetSurround$DurationInDays)
rangeDurationSurround
# summary
summarySurround <- summary(subsetSurround)
summarySurround

# ambush summary statistics
# means
meanShuSoldiersAmbush <- mean(subsetAmbush$ShuSoldiersEngaged)
meanShuSoldiersAmbush
meanWeiSoldiersAmbush <- mean(subsetAmbush$WeiSoldiersEngaged)
meanWeiSoldiersAmbush
meanDurationAmbush <- mean(subsetAmbush$DurationInDays)
meanDurationAmbush
# standard deviations
sdShuSoldiersAmbush <- sd(subsetAmbush$ShuSoldiersEngaged)
sdShuSoldiersAmbush
sdWeiSoldiersAmbush <- sd(subsetAmbush$WeiSoldiersEngaged)
sdWeiSoldiersAmbush
sdDurationAmbush <- sd(subsetAmbush$DurationInDays)
sdDurationAmbush
# ranges
rangeShuSoldiersAmbush <- range(subsetAmbush$ShuSoldiersEngaged)
rangeShuSoldiersAmbush
rangeWeiSoldiersAmbush <- range(subsetAmbush$WeiSoldiersEngaged)
rangeWeiSoldiersAmbush
rangeDurationAmbush <- range(subsetAmbush$DurationInDays)
rangeDurationAmbush
# summary
summaryAmbush <- summary(subsetAmbush)
summaryAmbush

# fire summary statistics
# means
meanShuSoldiersFire <- mean(subsetFire$ShuSoldiersEngaged)
meanShuSoldiersFire
meanWeiSoldiersFire <- mean(subsetFire$WeiSoldiersEngaged)
meanWeiSoldiersFire
meanDurationFire <- mean(subsetFire$DurationInDays)
meanDurationFire
# standard deviations
sdShuSoldiersFire <- sd(subsetFire$ShuSoldiersEngaged)
sdShuSoldiersFire
sdWeiSoldiersFire <- sd(subsetFire$WeiSoldiersEngaged)
sdWeiSoldiersFire
sdDurationFire <- sd(subsetFire$DurationInDays)
sdDurationFire
# ranges
rangeShuSoldiersFire <- range(subsetFire$ShuSoldiersEngaged)
rangeShuSoldiersFire
rangeWeiSoldiersFire <- range(subsetFire$WeiSoldiersEngaged)
rangeWeiSoldiersFire
rangeDurationFire <- range(subsetFire$DurationInDays)
rangeDurationFire
# summary
summaryFire <- summary(subsetFire)
summaryFire

##  QUANTIFYING CATEGORICAL VARIABLES

# represent categorical data numerically using as.numeric(data)
# recode the SuccessfullyExecuted column into N = 1 and Y = 2
numericExecutionHeadToHead <- as.numeric(subsetHeadToHead$SuccessfullyExecuted)
# display the contents of numericSuccessfullyExecutedHeadToHead
numericExecutionHeadToHead

# recode the SuccessfullyExecuted column into N = 0 and Y = 1
# by default, R recodes variables from 1 to n, so subtract one to offset the coding from 0 to n
numericExecutionHeadToHead <- as.numeric(subsetHeadToHead$SuccessfullyExecuted) - 1
# display the contents of numericExecutionHeadToHead
numericExecutionHeadToHead

# recode the Result column into Defeat = 0 and Victory = 1
numericResultHeadToHead <- as.numeric(subsetHeadToHead$Result) - 1
# display the contents of numericResultHeadToHead
numericResultHeadToHead

# quantify the SuccessfullyExecuted and Result columns for each battle method
# recode the SuccessfullyExecuted column into N = 0 and Y = 1
# recode the Result column into Defeat = 0 and Victory = 1
# display the contents of each variable

# surround
# SuccessfullyExecuted
numericExecutionSurround <- as.numeric(subsetSurround$SuccessfullyExecuted) - 1
numericExecutionSurround
# Result
numericResultSurround <- as.numeric(subsetSurround$Result) - 1
numericResultSurround

# ambush
# SuccessfullyExecuted
numericExecutionAmbush <- as.numeric(subsetAmbush$SuccessfullyExecuted) - 1
numericExecutionAmbush

# Result
numericResultAmbush <- as.numeric(subsetAmbush$Result) - 1
numericResultAmbush

# fire
# SuccessfullyExecuted
numericExecutionFire <- as.numeric(subsetFire$SuccessfullyExecuted) - 1
numericExecutionFire

# Result
numericResultFire <- as.numeric(subsetFire$Result) - 1
numericResultFire

# #  CORRELATING VARIABLES

# use cor(x,y) to calculate the correlation between two variables
# remember only to use numeric values when calculating correlations

# How is the performance rating of the Shu army related to the outcome of a head to head battle?
corRatingResultHeadToHead <- cor(subsetHeadToHead$Rating, numericResultHeadToHead)
# display the value of the correlation
corRatingResultHeadToHead

# How is the number of Shu soldiers engaged in a head to head battle correlated with the number of Wei soldiers engaged?
corShuWeiSoldiersHeadToHead <- cor(subsetHeadToHead$ShuSoldiersEngaged, subsetHeadToHead$WeiSoldiersEngaged)
# display the value of the correlation
corShuWeiSoldiersHeadToHead

# use cor(data) to calculate the correlation between all numeric variables in a dataset

# How are all of our numeric battle data correlated with one another?
corHeadToHead <- my_correlation(subsetHeadToHead)
# display the correlations
corHeadToHead

# NA values are introduced by nonnumeric data
# to correlate nonnumeric variables, we must first quantify them

# correlate Rating with Successfully Executed for each remaining battle method
# then correlate the entire subset
# display the result of each

# surround
# How is a battle's rating related to successful execution of the surround strategy?
corResultExecutionSurround <- cor(numericResultSurround, numericExecutionSurround)
corResultExecutionSurround
# What other correlations are present in the dataset?
corSurround <- my_correlation(subsetSurround)
corSurround

# ambush
# How is a battle's rating related to successful execution of the ambush strategy?
corResultExecutionAmbush <- cor(numericResultAmbush, numericExecutionAmbush)
corResultExecutionAmbush
# What other correlations are present in the dataset?
corAmbush <- my_correlation(subsetAmbush)
corAmbush

# fire
# How is a battle's rating related to successful execution of the fire attack strategy?
corResultExecutionFire <- cor(numericResultFire, numericExecutionFire)
corResultExecutionFire
# What other correlations are present in the dataset?
corFire <- my_correlation(subsetFire)
corFire

# #  REGRESSION

# #  MODELING WITH SIMPLE LINEAR REGRESSION

# create a linear regression model using the lm(formula, data)
# predict the rating of a head to head battle using the number of Shu soldiers engaged
lmHeadToHeadRating_ShuSoldiers <- lm(subsetHeadToHead$Rating ~ subsetHeadToHead$ShuSoldiersEngaged, subsetHeadToHead)
# display the contents of the model
lmHeadToHeadRating_ShuSoldiers

# create the model summary
lmHeadToHeadRating_ShuSoldiers_Summary <- summary(lmHeadToHeadRating_ShuSoldiers)
# display the model summary
lmHeadToHeadRating_ShuSoldiers_Summary


##  MODELING WITH MULTIPLE LINEAR REGRESSION

# create a multiple linear regression model using the lm(formula, data) function
# predict the rating of a head to head battle using the number of Shu and Wei soldiers engaged
lmHeadToHeadRating_ShuWeiSoldiers <- lm(subsetHeadToHead$Rating ~ subsetHeadToHead$ShuSoldiersEngaged + subsetHeadToHead$WeiSoldiersEngaged, subsetHeadToHead)
# model summary
lmHeadToHeadRating_ShuWeiSoldiers_Summary <- summary(lmHeadToHeadRating_ShuWeiSoldiers)
# display the summary
lmHeadToHeadRating_ShuWeiSoldiers_Summary

# predict the rating of a head to head battle using duration
lmHeadToHeadRating_Duration <- lm(subsetHeadToHead$Rating ~ subsetHeadToHead$DurationInDays, subsetHeadToHead)
# summary
lmHeadToHeadRating_Duration_Summary <- summary(lmHeadToHeadRating_Duration)
lmHeadToHeadRating_Duration_Summary

# predict the rating of a head to head battle using duration and the number of Shu soldiers
lmHeadToHeadRating_DurationShuSoldiers <- lm(subsetHeadToHead$Rating ~ subsetHeadToHead$DurationInDays + subsetHeadToHead$ShuSoldiersEngaged, subsetHeadToHead)
# summary
lmHeadToHeadRating_DurationShuSoldiers_Summary <- summary(lmHeadToHeadRating_DurationShuSoldiers)
lmHeadToHeadRating_DurationShuSoldiers_Summary 


# predict the rating of a head to head battle using duration and the number of Shu and Wei soldiers
lmHeadToHeadRating_DuratioSoldiers <- lm(subsetHeadToHead$Rating ~ subsetHeadToHead$DurationInDays + subsetHeadToHead$ShuSoldiersEngaged + subsetHeadToHead$WeiSoldiersEngaged, subsetHeadToHead)
# summary
lmHeadToHeadRating_DuratioSoldiers_Summary <- summary(lmHeadToHeadRating_DuratioSoldiers)
lmHeadToHeadRating_DuratioSoldiers_Summary 


# the duration of battle is very important in predicting the performance of the Shu army in a head to head conflict!

# #  MODELING INTERACTIONS

# before creating an interaction variable, the component variables must first be centered
# center a variable by subtracting its mean from each of its values
# center the number of Shu soldiers engaged
centeredShuSoldiersHeadToHead <- subsetHeadToHead$ShuSoldiersEngaged - mean(subsetHeadToHead$ShuSoldiersEngaged)
# center the number of Wei soldiers engaged
centeredWeiSoldiersHeadToHead <- subsetHeadToHead$WeiSoldiersEngaged - mean(subsetHeadToHead$WeiSoldiersEngaged)

# create an interaction variable by multiplying two or more centered variables
interactionSoldiersHeadToHead <- centeredShuSoldiersHeadToHead * centeredWeiSoldiersHeadToHead

# predict the rating of a battle using the duration, number of Shu and Wei soldiers engaged, and the interaction between the number of Shu and Wei soldiers engaged
lmHeadToHeadRating_DurationSoldiersShuWeiInteraction <- lm(subsetHeadToHead$Rating ~  subsetHeadToHead$DurationInDays + subsetHeadToHead$ShuSoldiersEngaged + subsetHeadToHead$WeiSoldiersEngaged + interactionSoldiersHeadToHead, subsetHeadToHead)

# model summary
lmHeadToHeadRating_DurationSoldiersShuWeiInteraction_Summary <- summary(lmHeadToHeadRating_DurationSoldiersShuWeiInteraction)
# display the summary
lmHeadToHeadRating_DurationSoldiersShuWeiInteraction_Summary



# #  COMPARING AND CHOOSING MODELS

# use HLR to compare different models
# first consider the models individually
# simple regression model using duration to predict battle rating
lmHeadToHeadRating_Duration_Summary
#Multiple R-squared: 0.7718

# multiple regression model using duration, Shu soldiers, and Wei soldiers to predict battle rating
lmHeadToHeadRating_DuratioSoldiers_Summary
#Multiple R-squared: 0.8585,	Adjusted R-squared: 0.8421 

# interaction model using duration, Shu soldiers, Wei soldiers, and the interaction between Shu and Wei soldiers to predict battle rating
lmHeadToHeadRating_DurationSoldiersShuWeiInteraction_Summary
#Multiple R-squared: 0.8653,	Adjusted R-squared: 0.8437 

# use anova(object, ...) to compare the relative contribution of multiple models
# compare the three head to head combat models using ANOVA
anovaHeadToHeadRatingModelComparison <- anova(lmHeadToHeadRating_Duration, lmHeadToHeadRating_DuratioSoldiers, lmHeadToHeadRating_DurationSoldiersShuWeiInteraction)
anovaHeadToHeadRatingModelComparison

# #  SAVE YOUR WORKSPACE AND CONSOLE TEXT

# save your R workspace using save.image(file)
# remember to include the .RData file extension
save.image("rBeginnersGuide_Ch_04_hero.RData")

# save your R console text by copying and pasting it into a text file